// 防抖函数
function debounce (func, delay) {
    var timer

    return function () {
        var args = [].slice.call(arguments)
        if (timer) {
            clearTimeout(timer)
        }
        timer = setTimeout(function () {
            func.apply(this, args)
        }, delay)
    }
}

$(function () {
    var query = $('.input_box').val()
    var pageNum = 0
    // 进入详情页后返回
    if (query) {
        pageNum = 0
        $('.hot-search').hide()
        sessionStorage.setItem(str + PAGENUM_KEY, pageNum)
        getGoodsData('/search?query=' + query + '&pageNum=' + pageNum)
    } else {
        sessionStorage.setItem(str + PAGENUM_KEY, 0)
        setScrollTop()
    }

    // 回到顶部
    $('.to-top').on('click', function () {
        $(window).scrollTop(0)
    })

    // 搜索历史记录
    var SEARCH_KEY = '__search__'
    getHistoryItem()
    function getHistoryItem () {
        var searchList = localStorage.getItem(SEARCH_KEY) ? localStorage.getItem(SEARCH_KEY).split(',') : []
        if (searchList.length === 0) {
            $('.search-history').hide()
            return
        }
        var searches = []
        var search
        searchList.forEach(function (item) {
            search = '<a href="#" class="search-item" data-query="' + item + '">' + item + '</a>'
            searches.push(search)
        })
        $('.search-history-list').html(searches.join(''))
        $('.search-history').show()
        $('.search-history-list .search-item').on('click', handleSearchClick)
    }

    function handleSearchClick (e) {
        $('.hot-search').hide()
        $('.search-history').hide()
        e.preventDefault()
        pageNum = 0
        query = $(this).data('query')
        $('.input_box').val(query)
        saveSearch(query)
        sessionStorage.setItem(str + PAGENUM_KEY, pageNum)
        setScrollTop(0)
        getGoodsData('/search?query=' + query + '&pageNum=' + pageNum)
    }

    $('.search-history-list .search-item').on('click', handleSearchClick)

    $('.delete-search').on('click', function (e) {
        e.preventDefault()
        clearSearch()
        $('.search-history').hide()
    })
    
    function handleInput (e) {
        sessionStorage.setItem(str + PAGENUM_KEY, 0)
        query = $('.input_box').val()
        if (!query) {
            query = undefined
            $('.commodity-list').html('')
            $('.search-history').show()
            $('.hot-search').show()
            $('#info').hide()
            $('#search-info').hide()
            getHistoryItem()
        }
    }
    $('.input_box').on('input', debounce(handleInput, 200))

    function goSearch () {
        $('.search-history').hide()
        $('.hot-search').hide()
        pageNum = 0
        isMore = true
        query = $('.input_box').val()
        if (!query) {
            $('.search-history').show()
            $('.hot-search').show()
            return
        }
        saveSearch(query)
        sessionStorage.setItem(str + PAGENUM_KEY, pageNum)
        getGoodsData('/search?query=' + query + '&pageNum=' + pageNum)
    }
    $('.submit-button').on('click', function () {
        goSearch()
    })

    $('.input_box').on('keydown', function (e) {
        if(e.keyCode ==13){
            goSearch()
            return false;
        }
    })

    // 热门推荐
    $.get('/querytip', function (data) {
        var hots = []
        data.forEach(function (item) {
            var hot = '<a href="#" class="hot-item" data-query="' + item + '">' + item + '</a>'
            hots.push(hot)
        })
        $('.hot-search-list').html(hots.join(''))
        $('.hot-search-list .hot-item').on('click', function (e) {
            e.preventDefault()
            pageNum = 0
            query = $(this).data('query')
            $('.input_box').val(query)
            saveSearch(query)
            sessionStorage.setItem(str + PAGENUM_KEY, pageNum)
            setScrollTop(0)
            getGoodsData('/search?query=' + query + '&pageNum=' + pageNum)
            $('.hot-search').hide()
            $('.search-history').hide()
        })
    })

    var PAGENUM_KEY = '__pageNum__'
    var isFirstLoad = false
    var href = window.location.href
    var str = href.substr(href.lastIndexOf('/') + 1) ? href.substr(href.lastIndexOf('/') + 1) : '/'
    var top = Number(sessionStorage.getItem(str))

    if (top === 0) {
        sessionStorage.setItem(str + PAGENUM_KEY, 0)
    }
    pageNum = Number(sessionStorage.getItem(str + PAGENUM_KEY))


    if (pageNum > 0) {
        $('.hot-search').hide()
        $.get('/search?query=' + query + '&pageNum=' + pageNum + '&all=all', function (data) {
            var goods = data.content.splice(20)
            var htmls = []
            goods.forEach(function (good, index) {
                var fragment =  Number(good.price) === Number(good.priceDiscount)
                    ? '<span>原价</span><span class="coupon-price">￥' + good.price + '</span>'
                    : '<span>券后</span><span class="coupon-price">￥' + good.priceDiscount + '</span>'

                var html =
                    '<div class="commodity-item">' +
                    '<a href="/good/' +  good.goodsId + '" > ' +
                    '<input type="hidden" id="goodsId" value="' + good.goodsId + '"/>' +
                    '<img class="lazy" src="http://owtl83r0c.bkt.clouddn.com/placeholder.gif" data="' + good.image + '"/>' +
                    '<span class="commodity-title">' + good.name + '</span> ' +
                    '<div class="commodity-coupon-info"> ' + fragment +
                    '<span class="alreadyBuy">' + good.alreadyBuy + '人已买</span> ' +
                    '</div> ' +
                    '</a> ' +
                    '<span class="hot">' +
                    '<img src="http://owtl83r0c.bkt.clouddn.com/hot.png" />' +
                    '</span>' +
                    '<span class="coupon-banner">' +
                    '<span class="coupon-banner-left">' + '￥' + good.discount + '.0' + '</span>' +
                    '<span class="coupon-banner-right">领券</span>' +
                    '</span>' +
                    '</div>'
                htmls.push(html)
            })
            $('.commodity-list').append(htmls.join(''))
            $('img.lazy').lazyLoad()
            setTimeout(function () {
                $(window).scrollTop(top)
                isFirstLoad = true
                $('.commodity-list').on('click', 'a', function (e) {
                    var id = $(this).find('#goodsId').val()
                    e.preventDefault()
                    window.location.href = '/good/' + id
                    setScrollTop()
                })
            }, 200)

        })
    } else {
        isFirstLoad = true
    }

    function setScrollTop (num) {
        var href = window.location.href
        var str = href.substr(href.lastIndexOf('/') + 1) ? href.substr(href.lastIndexOf('/') + 1) : '/'
        var scrollTop = num ? num : $(window).scrollTop()
        sessionStorage.setItem(str, scrollTop)
    }

    function getGoodsData (url) {
        $.get(url, function (res) {
            var content = res.content
            var goods = []
            if (content.length > 0) {
                content.forEach(function (good) {
                    var fragment =  Number(good.price) === Number(good.priceDiscount)
                        ? '<span>原价</span><span class="coupon-price">￥' + good.price + '</span>'
                        : '<span>券后</span><span class="coupon-price">￥' + good.priceDiscount + '</span>'

                    var html =
                        '<div class="commodity-item">' +
                        '<a href="#">' +
                        '<input type="hidden" id="goodsId" value="' + good.goodsId + '"/>' +
                        '<img class="lazy" src="http://owtl83r0c.bkt.clouddn.com/placeholder.gif" data="' + good.image + '"/>' +
                        '<span class="commodity-title">' + good.name + '</span> ' +
                        '<div class="commodity-coupon-info"> ' + fragment +
                        '<span class="alreadyBuy">' + good.alreadyBuy + '人已买</span> ' +
                        '</div> ' +
                        '</a> ' +
                        '<span class="coupon-banner">' +
                        '<span class="coupon-banner-left">' + '￥' + good.discount + '.0' + '</span>' +
                        '<span class="coupon-banner-right">领券</span>' +
                        '</span>' +
                        '</div>'
                    goods.push(html)
                })
                $('.commodity-item').remove()
                $('#search-info').hide()
                $('.search-history').hide()
                $('.commodity-list').append(goods.join(''))
                $('img.lazy').lazyLoad()
            } else {
                $('.commodity-item').remove()
                $('#search-info').show()
            }
            $('.commodity-list').on('click', 'a', function (e) {
                var id = $(this).find('#goodsId').val()
                e.preventDefault()
                window.location.href = '/good/' + id
                setScrollTop()
            })
        })
    }

    var windowHeight = $(window).height(),
        windowScrollTop = 0,
        documentHeight = 0,
        isLoad = false,
        isMore = true
    $(window).on('scroll', function () {
        windowScrollTop = $(window).scrollTop()
        documentHeight = $(document).height()
        if (windowScrollTop + windowHeight >= documentHeight && !isLoad && isMore && isFirstLoad) {
            loadMore()
        }
        // 控制小火箭显示影藏
        if (windowScrollTop > 0) {
            $('.to-top').css('display', 'flex')
        } else {
            $('.to-top').css('display', 'none')
        }
    })

    function loadMore () {
        if (query == undefined) {
            $('#info').hide()
            return
        }
        pageNum = Number(sessionStorage.getItem(str + PAGENUM_KEY)) + 1
        console.log('loade' + pageNum)
        sessionStorage.setItem(str + PAGENUM_KEY, pageNum)
        isLoad = true
        $('#loading').show()
        $.get('/search?query=' + query + '&pageNum=' + pageNum, function (data) {
            isLoad = false
            var goods = data.content
            if (goods.length === 0) {
                $('#loading').hide()
                $('#info').show()
                isMore = false
                return
            }
            var htmls = []
            goods.forEach(function (good, index) {
                var fragment =  Number(good.price) === Number(good.priceDiscount)
                    ? '<span>原价</span><span class="coupon-price">￥' + good.price + '</span>'
                    : '<span>券后</span><span class="coupon-price">￥' + good.priceDiscount + '</span>'

                var html =
                    '<div class="commodity-item">' +
                        '<a href="#" > ' +
                            '<input type="hidden" id="goodsId" value="' + good.goodsId + '"/>' +
                            '<img class="lazy" src="http://owtl83r0c.bkt.clouddn.com/placeholder.gif" data="' + good.image + '"/>' +
                            '<span class="commodity-title">' + good.name + '</span> ' +
                            '<div class="commodity-coupon-info"> ' + fragment +
                                '<span class="alreadyBuy">' + good.alreadyBuy + '人已买</span> ' +
                            '</div> ' +
                        '</a> ' +
                        '<span class="coupon-banner">' +
                            '<span class="coupon-banner-left">' + '￥' + good.discount + '.0' + '</span>' +
                            '<span class="coupon-banner-right">领券</span>' +
                        '</span>' +
                    '</div>'
                htmls.push(html)
            })
            $('#loading').hide()
            $('.commodity-list').append(htmls.join(''))
            $('img.lazy').lazyLoad()
            $('.commodity-list').on('click', 'a', function (e) {
                var id = $(this).find('#goodsId').val()
                e.preventDefault()
                window.location.href = '/good/' + id
                setScrollTop()
            })
        })
    }

})